<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>订单详情</p>
      <span></span>
    </header>

    <div v-if="loading" class="loading">
      <p>加载中...</p>
    </div>

    <div v-else-if="order" class="order-detail">
      <!-- 订单状态卡片 -->
      <div class="status-card">
        <div class="status-header">
          <div class="status-info">
            <span class="order-number">订单号：{{ order.orderId }}</span>
            <span class="order-time">{{ formatDate(order.orderDate) }}</span>
          </div>
          <div class="status-badge" :class="getStatusClass(order.orderState)">
            {{ getStatusText(order.orderState) }}
          </div>
        </div>
        
        <!-- 订单进度条 -->
        <div class="progress-bar">
          <div class="progress-step" :class="{ active: order.orderState >= 1, completed: order.orderState > 1 }">
            <div class="step-circle">1</div>
            <span>下单</span>
          </div>
          <div class="progress-line" :class="{ active: order.orderState > 1 }"></div>
          <div class="progress-step" :class="{ active: order.orderState >= 2, completed: order.orderState > 2 }">
            <div class="step-circle">2</div>
            <span>支付</span>
          </div>
          <div class="progress-line" :class="{ active: order.orderState > 2 }"></div>
          <div class="progress-step" :class="{ active: order.orderState >= 3, completed: order.orderState > 3 }">
            <div class="step-circle">3</div>
            <span>制作</span>
          </div>
          <div class="progress-line" :class="{ active: order.orderState > 3 }"></div>
          <div class="progress-step" :class="{ active: order.orderState >= 4 }">
            <div class="step-circle">4</div>
            <span>完成</span>
          </div>
        </div>
      </div>

      <!-- 客户信息 -->
      <div class="info-card">
        <h3><i class="fa fa-user"></i> 客户信息</h3>
        <div class="info-item">
          <span class="label">用户ID：</span>
          <span class="value">{{ order.userId }}</span>
        </div>
        <div class="info-item">
          <span class="label">下单时间：</span>
          <span class="value">{{ formatDate(order.orderDate) }}</span>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="info-card">
        <h3><i class="fa fa-cutlery"></i> 商品清单</h3>
        <div class="food-list" v-if="order.list && order.list.length > 0">
          <div class="food-item" v-for="item in order.list" :key="item.foodId">
            <img :src="getFoodImage(item.foodId)" alt="商品图片">
            <div class="food-info">
              <div class="food-name">{{ item.food?.foodName || '商品' }}</div>
              <div class="food-price">¥{{ item.food?.foodPrice || 0 }}</div>
            </div>
            <div class="food-quantity">
              <span>× {{ item.quantity }}</span>
              <span class="item-total">¥{{ ((item.food?.foodPrice || 0) * item.quantity).toFixed(2) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单金额 -->
      <div class="info-card">
        <h3><i class="fa fa-money"></i> 订单金额</h3>
        <div class="amount-detail">
          <div class="amount-item">
            <span>商品总额：</span>
            <span>¥{{ getItemsTotal().toFixed(2) }}</span>
          </div>
          <div class="amount-item">
            <span>配送费：</span>
            <span>¥{{ getDeliveryFee().toFixed(2) }}</span>
          </div>
          <div class="amount-item total">
            <span>订单总额：</span>
            <span>¥{{ order.orderTotal.toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons" v-if="order.orderState > 0 && order.orderState !== 0 && order.orderState !== -1">
        <!-- 待接单状态 (orderState = 2) -->
        <template v-if="order.orderState === 2">
          <button class="btn-accept" @click="updateOrderStatus(3)">
            <i class="fa fa-check"></i> 接受订单
          </button>
          <button class="btn-reject" @click="updateOrderStatus(0)">
            <i class="fa fa-times"></i> 拒绝订单
          </button>
        </template>

        <!-- 制作中状态 (orderState = 3) -->
        <template v-else-if="order.orderState === 3">
          <button class="btn-delivery" @click="updateOrderStatus(4)">
            <i class="fa fa-truck"></i> 开始配送
          </button>
          <button class="btn-refund" @click="refundOrder">
            <i class="fa fa-undo"></i> 申请退单
          </button>
        </template>

        <!-- 已完成状态 (orderState = 4) -->
        <template v-else-if="order.orderState === 4">
          <div class="completed-message">
            <i class="fa fa-check-circle"></i>
            <span>订单已完成</span>
          </div>
        </template>

        <!-- 申请退款状态 (orderState = 5) -->
        <template v-else-if="order.orderState === 5">
          <div class="refund-pending-message">
            <i class="fa fa-clock-o"></i>
            <span>顾客申请退款，等待处理</span>
          </div>
          <button class="btn-manage-refund" @click="goToRefundManagement">
            <i class="fa fa-cog"></i> 处理退款申请
          </button>
        </template>

        <!-- 已退款状态 (orderState = 6) -->
        <template v-else-if="order.orderState === 6">
          <div class="refunded-message">
            <i class="fa fa-check-circle"></i>
            <span>已同意退款</span>
          </div>
        </template>

        <!-- 已拒绝状态 (orderState = 0) -->
        <template v-else-if="order.orderState === 0">
          <div class="rejected-message">
            <i class="fa fa-times-circle"></i>
            <span>订单已拒绝</span>
          </div>
        </template>
        
        <!-- 已取消状态 (orderState = 0) -->
        <template v-else-if="order.orderState === 0">
          <div class="canceled-message">
            <i class="fa fa-ban"></i>
            <span>订单已取消</span>
          </div>
        </template>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-state">
      <i class="fa fa-exclamation-triangle"></i>
      <p>订单不存在或加载失败</p>
      <button class="btn-retry" @click="loadOrderDetail">重新加载</button>
    </div>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from "vue-router";
import { ref, inject, onMounted } from "vue";
import { getSessionStorage } from "../common.js";

// 导入商品图片
import sp01 from '@/assets/sp01.png'
import sp02 from '@/assets/sp02.png'
import sp03 from '@/assets/sp03.png'
import sp04 from '@/assets/sp04.png'
import sp05 from '@/assets/sp05.png'
import sp06 from '@/assets/sp06.png'
import sp07 from '@/assets/sp07.png'
import sp08 from '@/assets/sp08.png'
import sp09 from '@/assets/sp09.png'
import sp10 from '@/assets/sp10.png'
import sp11 from '@/assets/sp11.png'
import sp12 from '@/assets/sp12.png'

const axios = inject("axios");
const router = useRouter();
const route = useRoute();

const order = ref(null);
const loading = ref(true);
const business = ref(null);

// 获取商品图片
const getFoodImage = (foodId) => {
  const imageMap = {
    1: sp01, 2: sp02, 3: sp03, 4: sp04, 5: sp05, 6: sp06,
    7: sp07, 8: sp08, 9: sp09, 10: sp10, 11: sp11, 12: sp12
  }
  return imageMap[(foodId % 12) + 1] || sp01
}

// 返回上一页
const goBack = () => {
  router.push({ path: '/businessOrders' });
};

// 获取订单状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 0: return 'status-canceled';
    case 1: return 'status-pending';
    case 2: return 'status-waiting';
    case 3: return 'status-accepted';
    case 4: return 'status-completed';
    case 5: return 'status-refund-pending';
    case 6: return 'status-refunded';
    default: return '';
  }
};

// 获取订单状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '已取消/已拒绝';
    case 1: return '待支付';
    case 2: return '待接单';
    case 3: return '制作中';
    case 4: return '已完成';
    case 5: return '申请退款';
    case 6: return '已退款';
    default: return '未知状态';
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  try {
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    return dateStr;
  }
};

// 计算商品总额
const getItemsTotal = () => {
  if (!order.value?.list) return 0;
  return order.value.list.reduce((total, item) => {
    return total + (item.food?.foodPrice || 0) * item.quantity;
  }, 0);
};

// 计算配送费
const getDeliveryFee = () => {
  if (!order.value) return 0;
  const itemsTotal = getItemsTotal();
  return order.value.orderTotal - itemsTotal;
};

// 更新订单状态
const updateOrderStatus = async (newStatus) => {
  const statusTexts = {
    2: '接受订单',
    3: '接受订单',
    4: '完成订单',
    0: '拒绝订单'
  };
  
  if (!confirm(`确定要${statusTexts[newStatus]}吗？`)) {
    return;
  }
  
  try {
    loading.value = true;
    console.log(`开始${statusTexts[newStatus]}，订单ID: ${order.value.orderId}，目标状态: ${newStatus}`);
    
    const response = await axios.put(`/api/orders/${order.value.orderId}/status?status=${newStatus}`);
    console.log(`${statusTexts[newStatus]}响应:`, response);
    
    // 更全面的响应判断
    if (response) {
      // 直接检查订单对象的id属性
      if (response === 1 || response.success || response.id || (response.data && response.data.id)) {
        alert(`${statusTexts[newStatus]}成功！`);
        order.value.orderState = newStatus;
        // 短暂延迟后返回订单列表
        setTimeout(() => {
          goBack();
        }, 1500);
      } else {
        console.error(`${statusTexts[newStatus]}失败，响应不符合预期:`, response);
        alert('操作失败，请重试');
      }
    } else {
      console.error(`${statusTexts[newStatus]}失败，响应为空`);
      alert('操作失败，服务器无响应');
    }
  } catch (error) {
    console.error("更新订单状态失败:", error);
    alert(`操作失败: ${error.message || '请检查网络连接'}`);
  } finally {
    loading.value = false;
  }
};

// 退单处理
const refundOrder = async () => {
  if (!confirm('确定要申请退单吗？退单后订单将被取消。')) {
    return;
  }
  
  try {
    loading.value = true;
    console.log(`开始申请退单，订单ID: ${order.value.orderId}`);
    
    const response = await axios.put(`/api/orders/${order.value.orderId}/status?status=0`);
    console.log("退单响应:", response);
    
    // 更全面的响应判断
    if (response) {
      // 直接检查订单对象的id属性
      if (response === 1 || response.success || response.id || (response.data && response.data.id)) {
        alert('退单成功！');
        order.value.orderState = 0;
        // 短暂延迟后返回订单列表
        setTimeout(() => {
          goBack();
        }, 1500);
      } else {
        console.error("退单失败，响应不符合预期:", response);
        alert('退单失败，请重试');
      }
    } else {
      console.error("退单失败，响应为空");
      alert('操作失败，服务器无响应');
    }
  } catch (error) {
    console.error("退单失败:", error);
    alert(`退单失败: ${error.message || '请检查网络连接'}`);
  } finally {
    loading.value = false;
  }
};

// 加载订单详情
const loadOrderDetail = async () => {
  const orderId = route.params.orderId || route.query.orderId;
  if (!orderId) {
    alert('订单ID不存在');
    goBack();
    return;
  }
  
  try {
    loading.value = true;
    console.log("正在加载订单详情，订单ID:", orderId);
    
    // 使用标准RESTful API路径
    const response = await axios.get(`/api/orders/${orderId}`);
    console.log("订单详情API响应:", response);
    
    // 获取订单商品详情
    const detailetsResponse = await axios.get(`/api/orders/${orderId}/detailets`);
    console.log("订单商品详情API响应:", detailetsResponse);
    
    if (response) {
      // 处理订单基本信息
      order.value = {
        ...response,
        orderId: response.id,
        list: Array.isArray(detailetsResponse) ? detailetsResponse : []
      };
      console.log("成功加载订单详情:", order.value);
    } else {
      order.value = null;
      console.log("订单详情响应无效");
    }
  } catch (error) {
    console.error("加载订单详情失败:", error);
    order.value = null;
    alert('加载订单详情失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 页面初始化
onMounted(() => {
  // 检查登录状态
  const sessionBiz = getSessionStorage("business");
  const localBizStr = localStorage.getItem("business");
  const localBiz = localBizStr ? JSON.parse(localBizStr) : null;
  const businessInfo = sessionBiz || localBiz;
  if (!businessInfo) {
    alert("请先登录！");
    router.push({ path: '/businessLogin' });
    return;
  }
  
  business.value = businessInfo;
  console.log("当前登录商家:", business.value);
  
  // 加载订单详情
  loadOrderDetail();
});

// 跳转到退款管理页面
const goToRefundManagement = () => {
  router.push('/businessRefunds');
};
</script>

<style scoped>
.wrapper {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;
}

/* header样式 */
header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.5vw;
  
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4vw;
}

header .fa-angle-left {
  font-size: 5vw;
  cursor: pointer;
}

/* 主要内容区域 */
.order-detail {
  margin-top: 14vw;
  padding: 0 3vw;
}

/* 状态卡片 */
.status-card {
  background-color: #fff;
  border-radius: 2vw;
  padding: 4vw;
  margin-bottom: 3vw;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 4vw;
}

.status-info {
  display: flex;
  flex-direction: column;
}

.order-number {
  font-size: 4vw;
  font-weight: bold;
  color: #333;
  margin-bottom: 1vw;
}

.order-time {
  font-size: 3vw;
  color: #999;
}

.status-badge {
  padding: 1.5vw 3vw;
  border-radius: 1.5vw;
  font-size: 3vw;
  font-weight: bold;
}

.status-pending { background-color: #fff3cd; color: #856404; }
.status-accepted { background-color: #cce5ff; color: #0066cc; }
.status-delivery { background-color: #ffe6cc; color: #cc6600; }
.status-completed { background-color: #d4edda; color: #155724; }
.status-rejected { background-color: #f8d7da; color: #721c24; }
.status-refund-pending {
  color: #ff9800;
  background-color: #fff3e0;
}

.status-refunded {
  color: #f44336;
  background-color: #ffebee;
}

/* 进度条 */
.progress-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.progress-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.step-circle {
  width: 8vw;
  height: 8vw;
  border-radius: 50%;
  background-color: #ddd;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 3vw;
  font-weight: bold;
  margin-bottom: 1vw;
}

.progress-step.active .step-circle {
  background-color: #0097ff;
  color: #fff;
}

.progress-step.completed .step-circle {
  background-color: #27ae60;
  color: #fff;
}

.progress-step span {
  font-size: 2.5vw;
  color: #666;
}

.progress-line {
  height: 2px;
  background-color: #ddd;
  flex: 1;
  margin: 0 2vw;
}

.progress-line.active {
  background-color: #0097ff;
}

/* 信息卡片 */
.info-card {
  background-color: #fff;
  border-radius: 2vw;
  padding: 4vw;
  margin-bottom: 3vw;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.info-card h3 {
  font-size: 4vw;
  color: #333;
  margin: 0 0 3vw 0;
  display: flex;
  align-items: center;
}

.info-card h3 .fa {
  margin-right: 2vw;
  color: #0097ff;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2vw 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 3.5vw;
  color: #666;
}

.value {
  font-size: 3.5vw;
  color: #333;
  font-weight: bold;
}

/* 商品列表 */
.food-list {
  margin-top: 2vw;
}

.food-item {
  display: flex;
  align-items: center;
  padding: 3vw 0;
  border-bottom: 1px solid #f0f0f0;
}

.food-item:last-child {
  border-bottom: none;
}

.food-item img {
  width: 12vw;
  height: 12vw;
  border-radius: 1.5vw;
  margin-right: 3vw;
}

.food-info {
  flex: 1;
}

.food-name {
  font-size: 3.5vw;
  color: #333;
  margin-bottom: 1vw;
}

.food-price {
  font-size: 3vw;
  color: #0097ff;
  font-weight: bold;
}

.food-quantity {
  text-align: right;
}

.food-quantity span {
  display: block;
  font-size: 3vw;
  color: #666;
}

.item-total {
  color: #333 !important;
  font-weight: bold !important;
  margin-top: 1vw;
}

/* 金额详情 */
.amount-detail {
  margin-top: 2vw;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2vw 0;
  font-size: 3.5vw;
  color: #666;
}

.amount-item.total {
  border-top: 1px solid #f0f0f0;
  margin-top: 2vw;
  padding-top: 3vw;
  font-size: 4vw;
  color: #333;
  font-weight: bold;
}

.amount-item.total span:last-child {
  color: #e74c3c;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 3vw;
  margin-top: 4vw;
}

.action-buttons button {
  flex: 1;
  height: 12vw;
  border: none;
  border-radius: 2vw;
  font-size: 3.5vw;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-buttons .fa {
  margin-right: 1vw;
}

.btn-accept {
  background-color: #27ae60;
  color: #fff;
}

.btn-accept:hover {
  background-color: #219a52;
}

.btn-reject {
  background-color: #e74c3c;
  color: #fff;
}

.btn-reject:hover {
  background-color: #c0392b;
}

.btn-delivery {
  background-color: #f39c12;
  color: #fff;
}

.btn-delivery:hover {
  background-color: #e67e22;
}

.btn-complete {
  background-color: #3498db;
  color: #fff;
}

.btn-complete:hover {
  background-color: #2980b9;
}

.btn-refund {
  background-color: #95a5a6;
  color: #fff;
}

.btn-refund:hover {
  background-color: #7f8c8d;
}

/* 完成和拒绝消息 */
.completed-message,
.rejected-message,
.canceled-message {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4vw;
  border-radius: 2vw;
  font-size: 4vw;
  font-weight: bold;
}

.completed-message {
  background-color: #d4edda;
  color: #155724;
}

.rejected-message {
  background-color: #f8d7da;
  color: #721c24;
}

.canceled-message {
  background-color: #f0f0f0;
  color: #666;
}

.completed-message .fa,
.rejected-message .fa,
.canceled-message .fa {
  margin-right: 2vw;
  font-size: 5vw;
}

.refund-pending-message {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 16px;
  color: #ff9800;
  margin-bottom: 16px;
}

.refunded-message {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 16px;
  color: #f44336;
}

.btn-manage-refund {
  padding: 12px;
  background-color: #ff9800;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  transition: background-color 0.3s;
}

.btn-manage-refund:hover {
  background-color: #f57c00;
}

/* 加载和错误状态 */
.loading,
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8vw;
  margin-top: 14vw;
  color: #999;
  text-align: center;
}

.error-state .fa {
  font-size: 12vw;
  color: #e74c3c;
  margin-bottom: 3vw;
}

.btn-retry {
  margin-top: 4vw;
  padding: 3vw 6vw;
  background-color: #0097ff;
  color: #fff;
  border: none;
  border-radius: 2vw;
  font-size: 3.5vw;
  cursor: pointer;
}

/* 响应式适配 */
@media (max-width: 480px) {
  header {
    height: 50px;
    padding: 0 16px;
  }
  
  .order-detail {
    margin-top: 60px;
    padding: 0 12px;
  }
  
  .status-card,
  .info-card {
    padding: 16px;
    margin-bottom: 12px;
  }
  
  .order-number {
    font-size: 16px;
  }
  
  .order-time {
    font-size: 12px;
  }
  
  .status-badge {
    font-size: 12px;
    padding: 6px 12px;
  }
  
  .step-circle {
    width: 32px;
    height: 32px;
    font-size: 12px;
  }
  
  .action-buttons button {
    height: 48px;
    font-size: 14px;
  }
}
</style> 